#! /bin/bash

# This script make both full and incremental backups for a given directory.
# The output file will have the following format:
#        directory_name.date.f.tarz       in case of full backup
#        directory_name.date.i.tarz       in case of incremental backup
#-------------------------------------------------------------------------
# Copyright (c) 2011 Andres Medina 
# This script is licensed under GNU GPL version 2.0 or above
# 
#-------------------------------------------------------------------------
# Last updated on : 07-December-2011
# 
#-------------------------------------------------------------------------

echo "RUNNING ............................"

#                FUNCTIONS

# makes a backup of the whole directory
#-------------------------------------------------------------------------
full_backup(){  
  # set the backup directory, date and the zip file name
  BACKUP_DIR=$2
  DATE=$(date +%F)
  ZIP_NAME=$2.$DATE.$1

  # check if the backup directory exist and if it's a directory
  if [ ! -d ./$BACKUP_DIR ]; then
    echo "ERROR: The directory $BACKUP_DIR doesn't exist or it's not a directory"
    exit 1;
  fi
  
  # create the compress file <archive.tarz> with the format directory_name.date.f|i.tarz
  if ! tar czf $ZIP_NAME.tarz $BACKUP_DIR; then
    echo "ERROR: Compress error, couldn't created the tarz file";
  else
    echo "$ZIP_NAME.tarz create successfully";
  fi

}



# makes a incremental backup of the directory
#------------------------------------------------------------------------- 
partial_backup(){
  # set the backup directory, date and the zip file name
  BACKUP_DIR=$2
  DATE=$(date +%F)
  ZIP_NAME=$2.$DATE.$1

  # check if the backup directory exist and if it's a directory
  if [ ! -d ./$BACKUP_DIR ]; then
    echo "ERROR: The directory $BACKUP_DIR doesn't exist or it's not a directory"
    exit 1;
  fi

# FALTA AVERIGUAR QUE ES UN PARTIAL BACKUP Y TERMINAR LA IMPLEMENTACION

}



# recover the files in the backup file <archive.tarz>
#------------------------------------------------------------------------- 
recover_backup(){
  # sets the working directory and the file with the backup
  WORK_DIR=$(pwd)
  RECOVER_FILE=$2

  # check if the recover file exist
  if [ ! -e ./$RECOVER_FILE ]; then
    echo "ERROR: The file $RECOVER_FILE doesn't exist"
    exit 1;
  fi

  # extract the content of the <archive.tarz> file in the working directory
  if ! tar xzf $WORKING_DIR ./$RECOVER_FILE; then
    echo "ERROR: Compress error, couldn't created the tarz file";
  else
    echo "Backup in $RECOVER_FILE successfully extracted";
  fi

}


#              MAIN PROGRAM
#
#-----------------------------------------------------------------------

# calls the right function according to the flag given by the user
case $1 in 
  f) full_backup;;
  i) partial_backup;;
  r) recover_backup;;
  *) echo "ERROR: wrong syntaxis";;
esac
